﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RuleCode.Table;
using RuleCode.Common;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;

namespace chatblog.CommonChat
{
    public partial class CommonChatRoom : System.Web.UI.Page
    {
        #region 页面加载
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(CommonChatRoom));
            cbuser.dealcookie();

            if (!IsPostBack)
            {
                if (!ParamsStatus())
                {
                    string scriptStr = "alert('对不起，您没有权限打开该聊天室！');window.opener =null;window.open('','_self','');window.close(); ";
                    bool isFF = Request.UserAgent.ToLower().Contains("firefox");
                    if (isFF)
                        scriptStr = "document.getElementById('ctl00_ctl00_login1_Button_loginout').click();" + scriptStr;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hasLogin", "<script type=\"text/javascript\">" + scriptStr + "</script>", false);
                    return;
                }

                if (Request[ParamID] != null && Request[ParamType] != null)
                {
                    CurrentRoomTitle = ResolveRoomTitleFormType(Request[ParamType], Request[ParamID]);
                    this.Title = "聊天室_" + CurrentRoomTitle;
                }
                InitChat();
                BindUserCate();
                
            }
        }
        #endregion

        #region 静态字段
        private static string ParamID = "ID";
        private static string ParamType = "Type";
        private static string DefaultDoorPInnerHTML = "<h2  class=\"h2style\" id=\"702743\">在线用户</h2><div class=\"content\"  style=\" background-color :#ECECEC ;  overflow :visible ;\" >  </div>";
        private static string systemUserId = "系统消息";
        #endregion

        #region 当前聊天室相关
        [AjaxPro.AjaxProperty]
        public string currentUserID
        {
            get
            {
                return AliApi.appUserId;
            }

        }

        //private string currentRoomID = string.Empty;
        /// <summary>
        /// 获取或设置当前聊天室ID
        /// </summary>
        public string CurrentRoomID
        {
            get
            {
                if (ViewState ["RoomID"] == null)
                    return string.Empty;
                return ViewState["RoomID"].ToString();

            }
            set
            {
                ViewState["RoomID"] = value;
            }
        }

        /// <summary>
        /// 获取或设置当前聊天室的 标题
        /// </summary>
        public string CurrentRoomTitle
        {
            get
            {
                if (Session["RoomTitle"] == null)
                    Session["RoomTitle"] = "";
                return Session["RoomTitle"].ToString();
            }
            set
            {
                Session["RoomTitle"] = value;
            }
        }        

        /// <summary>
        /// 根据 RoomType 获取 标题
        /// </summary>
        /// <param name="roomType"></param>
        /// <returns></returns>
        private string ResolveRoomTitleFormType(string paramTypeValue,string paramIDValue)
        {
            string roomTitle = string.Empty;
            roomTitle = zfunction.getfromchatroomid(paramTypeValue, paramIDValue);
            return roomTitle;
        }

        /// <summary>
        /// 把当前的RoomID存储到页面上去
        /// </summary>
        /// <param name="roomID"></param>
        private void SaveRoomIDToClient(string roomID)
        {
            this.RoomIDHidden.Value = roomID;   
            //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hasLogin", "<script type=\"text/javascript\">" + "document.getElementById('RoomIDHidden').value='" +roomID + "';</script>", false);
        }
        #endregion

        #region 绑定分组和右键菜单
        [AjaxPro.AjaxMethod]
        public string GetCurrentUserID()
        {
            return currentUserID;
        }

        [AjaxPro .AjaxMethod ]
        public string GetCurrentRoomTitle()
        {
            return CurrentRoomTitle;
        }

        /// <summary>
        /// 获取参数是否传递正确
        /// </summary>
        /// <returns></returns>
        private bool ParamsStatus()
        {
            return !(Request[ParamID] == null || Request[ParamID].Trim() == string.Empty || Request[ParamType] == null || Request[ParamType].Trim() == string.Empty);
        }

        private bool ValidateRoomUserStatus()
        { 
            return ( currentUserID !=null&&currentUserID !=string.Empty );
        }

        public bool InitChat()
        {
            if (currentUserID == null || currentUserID.Trim() == string.Empty)
                return false;
            if (ParamsStatus() == false)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hasLogin", "<script type=\"text/javascript\">" +"" + "</script>", false);
                return false;
            }

            string newUserID =AliApi .appUserId ;
            string newUserNick = AliApi.appNickName ;   //需要？？？？
            string roomFilter = "RoomType='"+Request [ParamID]+"'";
            DataRow[] roomRows = CommonChatRoomCache.ChatRoomTable.Select(roomFilter );
            //聊天室已经创建
            if (roomRows.Length > 0)
            {
                string userFilter = "UserID='"+newUserID+"' and RoomID='"+roomRows [0]["RoomID"].ToString ()+"'";
                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select(userFilter);
                //聊天室已经打开
                if (userRows.Length > 0)
                {
                    string scriptStr = "alert('对不起，您在其他地方已经打开该聊天室！不能再打开该聊天室了！');document.location .href='../login/ChatSetup.aspx'; ";
                     ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hasLogin", "<script type=\"text/javascript\">" + scriptStr + "</script>", false);
                    //Response.Redirect(ResolveUrl("~/login/ChatSetup.aspx"));
                    return false;
                }
                else
                {
                    DataRow newUserRow = CommonChatRoomCache.ChatUserTable.NewRow();
                    newUserRow["UserID"] = newUserID;
                    newUserRow["RoomID"] = roomRows[0]["RoomID"].ToString();
                    newUserRow["NickName"] = newUserNick;
                    newUserRow["LastestChatInfoID"] = roomRows[0]["LastestChatInfoID"].ToString();
                    newUserRow["StartTime"] = DateTime.Now;
                    CommonChatRoomCache.ChatUserTable.Rows.Add(newUserRow);
                    CurrentRoomID = newUserRow["RoomID"].ToString();
                    SaveRoomIDToClient(newUserRow["RoomID"].ToString());
                    InsertNewMessage("欢迎 " + ((newUserNick != "" && newUserNick != null) ? newUserNick : newUserID) + " 进入聊天室！", true, CurrentRoomID);
                    return true;
                }
            }
            //聊天室未创建
            else
            {
                DateTime createdTime = DateTime.Now;
                string newRoomID =  CommonChatRoomCache.GetNewRoomID();
                DataRow newRoomRow = CommonChatRoomCache.ChatRoomTable.NewRow();
                newRoomRow["RoomID"] = newRoomID;
                newRoomRow["RoomType"] = Request[ParamID];
                newRoomRow["CreatedBy"] = newUserID;
                newRoomRow["CreatedTime"] = createdTime;
                newRoomRow["RoomName"] = CurrentRoomTitle ;
                newRoomRow["LastestChatInfoID"] = 0;
                CommonChatRoomCache.ChatRoomTable.Rows.Add(newRoomRow);

                DataRow newUserRow = CommonChatRoomCache.ChatUserTable.NewRow();
                newUserRow["UserID"] = newUserID;
                newUserRow["RoomID"] = newRoomID;
                newUserRow["NickName"] = newUserNick;
                newUserRow["LastestChatInfoID"] = newRoomRow["LastestChatInfoID"];
                newUserRow["StartTime"] = createdTime;
                CommonChatRoomCache.ChatUserTable.Rows.Add(newUserRow);

                CurrentRoomID = newRoomID;
                SaveRoomIDToClient(newRoomID);
                InsertNewMessage("祝贺 " + ((newUserNick != "" && newUserNick!=null)?newUserNick:newUserID ) + " 创建聊天室成功！", true,newRoomID );
                return true;
            }
        }

        public void BindUserCate()
        {
            this.DoorP.InnerHtml = "";
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "currentuser", "<script type=\"text/javascript\">currentUser = chatblog.CommonChat.CommonChatRoom.GetCurrentUserID().value;</script>", false);
            if (!ValidateRoomUserStatus ())
            {
                this.DoorP.InnerHtml = DefaultDoorPInnerHTML;
                return;
            }

            List<string> allFrields = GetCurrentUserFriends();
            string childCate = string.Empty;
            string childUser = string.Empty;
            string groupListFilter = string.Empty;
            DataRow[] chatUsers = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + CurrentRoomID + "'");
            if (CurrentRoomID.Trim() != string.Empty && chatUsers.Length > 0)
            {
                int count = chatUsers.Length;
                childCate = "<h2  class=\"h2style\" id=\"" + CommonChatRoomCache.DefaultGroupID + "\">" + CommonChatRoomCache.DefaultGroupName + "<a>(" + count.ToString() + ")</a></h2>";
                childCate += "<div class=\"content \">"; 
                foreach (DataRow dRow in chatUsers)
                {
                    string imgStr = string.Empty;
                    if (dRow["UserID"].ToString() == AliApi.appUserId)
                    {
                        imgStr = "<img alt=\"在线\" title=\"自己\"  src =\"img/self.gif\" />";
                    }
                    else
                    {
                        if (allFrields.Contains(dRow["UserID"].ToString()))
                            imgStr = "<img alt=\"在线\" title=\"该用户是好友\"  src =\"img/regular_smile.gif\" />";
                        else
                            imgStr = "<img alt=\"在线\" title=\"该用户尚未成为好友\"  src =\"img/notuser.ico\" />";
                    } 
                    childCate += "<span class=\"contextMenu0\"   id='" + dRow["UserID"].ToString() + "'title=\"" + dRow["UserID"].ToString() + "\" >"
                    + imgStr + dRow["NickName"].ToString() + "</span>" + "<br />";
                }
                childCate += "</div>";
                this.DoorP.InnerHtml += childCate;
            }
        }

        /// <summary>
        /// 获取 分组列表HTML代码
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetGroupListUlHtml(string userid)
        {
            string ulHtml = string.Empty;
            RuleCode.Table.cbusergroup userGroup = cbusergroup.Find("cbuserid='" + currentUserID + "'", " cbusergroupid ");
            if (userGroup.Count > 0)
            {
                do
                {
                    ulHtml += "<li id=\"" + userGroup.cbusergroupid.Value + "\" onclick=\"changeGroupId('" + userid + "','" + userGroup.cbusergroupid.Value + "')\" >" + userGroup.cbname.Value + "</li>";  //onclick=\"changeGroupId('dddd')\"
                } while (userGroup.Next());
            }
            return ulHtml;
        }

        [AjaxPro .AjaxMethod]
        public string  AddUserToGroup(string userid, string groupid)
        {
            string errorMsg = string.Empty;
            if (AliApi.appUserId != null && AliApi.appUserId.Trim() != string.Empty)
            {
                string sqlString = "select * from dbo.cbusergrouplist where cbusergroupid in (select cbusergroupid from dbo.cbusergroup where cbuserid=@myid) and cbuserid=@userid";
                SqlParameter[] sqlparams = new SqlParameter [2];
                sqlparams[0] = new SqlParameter("@myid", AliApi.appUserId);
                sqlparams[1] = new SqlParameter("@userid", userid);
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlString, sqlparams);
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                    errorMsg = "对不起，该用户已经是您的好友了！";
                else
                {
                    string filter = "cbusergroupid='" + groupid + "' and cbuserid='" + userid + "'";
                    cbusergrouplist grouplist = cbusergrouplist.Find(filter);
                    if (grouplist.Count > 0)
                        errorMsg = "对不起，该用户已经在您的好友分组“" + groupid + "”里了！";
                    else
                    {
                        int index = userid.IndexOf("@");
                        grouplist.New();
                        grouplist.cbuserid.Value = userid;
                        grouplist.cbusergroupid.Value = groupid;
                        grouplist.cbname.Value = userid.Substring(0, index);
                        grouplist.noacceptemail.Value = RuleCode.Enum.NoYes.Yes;
                        grouplist.nosendemail.Value = RuleCode.Enum.NoYes.Yes;
                        grouplist.Insert();
                        errorMsg = "添加好友成功！";
                    }
                }
            }
            return errorMsg;
        }
        #endregion

        #region 好友分组Ajax方法
        /// <summary>
        /// 获取右键菜单 HTML代码
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetDoorPInnerHtml(string currentRoomID)
        {
            if (currentUserID == null || currentUserID.Trim() == string.Empty)
                return DefaultDoorPInnerHTML;
            string html = string.Empty;
            string childCate = string.Empty;
            string childUser = string.Empty;
            string groupListFilter = string.Empty;
            DataRow[] chatUsers = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + currentRoomID + "'");
            if (currentRoomID.Trim() != string.Empty && chatUsers.Length > 0)
            {
                int count = chatUsers.Length;
                childCate = "<h2  class=\"h2style\" id=\"" + CommonChatRoomCache.DefaultGroupID + "\">" + CommonChatRoomCache.DefaultGroupName + "<a>(" + count.ToString() + ")</a></h2>";
                childCate += "<div class=\"content \">";
                foreach (DataRow dRow in chatUsers)
                {
                    string imgStr = "<img alt=\"在线\" title=\"该用户在线\"  src =\"img/regular_smile.gif\" />";
                    childCate += "<span class=\"contextMenu0\"   id='" + dRow["UserID"].ToString() + "'title=\"" + dRow["UserID"].ToString() + "\" >"
                    + imgStr + dRow["NickName"].ToString() + "</span>" + "<br />";
                }
                childCate += "</div>";
                html = childCate;
            }

            return html;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetUserInnerHTMLInDoorP(string userid)
        {
            List<string> allFrields = GetCurrentUserFriends();
            string result = string.Empty;
            DataRow[] dRows = CommonChatRoomCache.ChatUserTable.Select("UserID='" + userid + "'");
            if (dRows.Length > 0)
            {
                DataRow dRow = dRows[0];
                string imgStr = string.Empty;
                if (dRow["UserID"].ToString() == AliApi.appUserId)
                {
                    imgStr = "<img alt=\"在线\" title=\"自己\"  src =\"img/self.gif\" />";
                }
                else
                {
                    if (allFrields.Contains(dRow["UserID"].ToString()))
                        imgStr = "<img alt=\"在线\" title=\"该用户是好友\"  src =\"img/regular_smile.gif\" />";
                    else
                        imgStr = "<img alt=\"在线\" title=\"该用户尚未成为好友\"  src =\"img/notuser.ico\" />";
                }
                result = "<span class=\"contextMenu0\"   id='" + dRow["UserID"].ToString() + "'title=\"" + dRow["UserID"].ToString() + "\" >"
                + imgStr + dRow["NickName"].ToString() + "</span>" + "<br />";
            }
            return result;
        }
        #endregion 

        #region 聊天窗口Ajax
        [AjaxPro.AjaxMethod]
        public string GetNewGuid()
        {
            return Guid.NewGuid().ToString("N");
        }

        [AjaxPro.AjaxMethod]
        public void InsertNewMessage( string message,bool isSystemInfo,string currentRoomID)
        {
            DataRow newChatInfoRow = CommonChatRoomCache.ChatInfoTable.NewRow();
            if (isSystemInfo)
                newChatInfoRow["UserFrom"] = CommonChatRoomCache.SystemInfoUserID;
            else
                newChatInfoRow["UserFrom"] = AliApi.appUserId;
            newChatInfoRow["ChatInfoID"] = CommonChatRoomCache.GetNewChatInfoID();
            newChatInfoRow["SendTime"] = DateTime.Now;
            newChatInfoRow["ChatContent"] = message;
            newChatInfoRow["RoomID"] = currentRoomID;
            CommonChatRoomCache.ChatInfoTable.Rows.Add(newChatInfoRow );
        }

        [AjaxPro.AjaxMethod]
        public string ValidateUser(string userid, string pass)
        {
            string filter = "cbuserid='" + userid + "' and cbpassword='" + pass + "'";
            RuleCode.Table.cbuser cbuser = cbuser.Find(filter);
            if (cbuser.Count > 0)
            {
                AliApi.appUserId = userid;
                return userid;
            }
            return "";
        }

        /// <summary>
        /// 获取公开聊天记录
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetPublicChatInfoHtml(string currentRoomID)
        {
            string chatinfoHtml = string.Empty;
            if (currentUserID == "")
                return chatinfoHtml;
            Int64 maxChatInfoId = 0;
            Int64 minChatInfoId = Int64 .MaxValue ;
            Int64 userChatInfoId = Int64.MaxValue;
            Int64 chatRoomInfoId = Int64.MaxValue;
            DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("UserID='" + currentUserID + "' and RoomID='" + currentRoomID + "'");
            if (userRows.Length > 0)
            {
                try
                {
                    userChatInfoId = Convert.ToInt64(userRows[0]["LastestChatInfoID"]);
                }
                catch { }
            }
            DataRow[] chatRoomRows = CommonChatRoomCache.ChatRoomTable.Select("RoomID='" + currentRoomID + "'");
            if (chatRoomRows.Length > 0)
            {
                try
                {
                    chatRoomInfoId = Convert.ToInt64(chatRoomRows[0]["LastestChatInfoID"]);
                }
                catch { }
            }
            minChatInfoId = Math.Min(userChatInfoId, chatRoomInfoId);
            DataRow[] chatInfoRows = CommonChatRoomCache.ChatInfoTable.Select("RoomID='" + currentRoomID + "' and ChatInfoID>" + minChatInfoId.ToString());
            string childHtml = string.Empty;
            if (chatInfoRows.Length > 0)
            {
                foreach (DataRow dRow in chatInfoRows)
                {
                    if (dRow["UserFrom"].ToString() != CommonChatRoomCache.SystemInfoUserID )   //非系统消息
                    {                
        
                        string color = (dRow["UserFrom"].ToString() == currentUserID) ? "#308712" : "blue";
                        string nickname =   (dRow["UserFrom"].ToString() == currentUserID)?AliApi .appNickName :CommonChatRoomCache .GetNickNameFromUserID ( dRow["UserFrom"].ToString() );
                        childHtml = "<div  class =\"chatInfoRecord\">";
                        childHtml += "<span style =\" color:" + color + "; font-weight :bold ;\">" + nickname + "</span> ";
                        childHtml += "<span style =\"color:Gray\">(" + dRow["SendTime"].ToString() + ")</span> <br />";
                        childHtml += "<div style =\" padding-left :20px;\">";
                        childHtml += dRow["ChatContent"].ToString();
                        childHtml += "</div>";
                        childHtml += "</div>";
                    }
                    else                                              //系统消息
                    {
                        childHtml = "<div  class =\"systemchatInfoRecord\">";
                        childHtml += "<span style =\" color:#9D3C11; font-weight :bold ;\">" + dRow["UserFrom"].ToString() + "</span> ";
                        childHtml += "<span style =\"color:Gray\">(" + dRow["SendTime"].ToString() + ")</span> <br />";
                        childHtml += "<div style =\" padding-left :20px;\">";
                        childHtml += dRow["ChatContent"].ToString();
                        childHtml += "</div>";
                        childHtml += "</div>";
                    }
                    chatinfoHtml += childHtml;

                    Int64 chatId = Convert.ToInt64(dRow["ChatInfoID"]);
                    if (chatId > maxChatInfoId)
                        maxChatInfoId = chatId;
                }
                if (userRows.Length > 0)
                    userRows[0]["LastestChatInfoID"] = maxChatInfoId;
                if (chatRoomRows.Length > 0)
                    chatRoomRows[0]["LastestChatInfoID"] = maxChatInfoId;
            }

            return chatinfoHtml;
        }

        [AjaxPro.AjaxMethod]
        public string GetCurrentUser()
        {
            return AliApi.appUserId;
        }
        #endregion

        #region 聊天对象相关
        /// <summary>
        /// 获取 最新发消息的用户
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string[] getNewMsgUsers()
        {
            List<string> msgUsers = new List<string>();
            if (currentUserID != "")
            {
                string sqlText = "dbo.[GetNewMsgUsers] '" + currentUserID + "'";
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlText);
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dRow in dSet.Tables[0].Rows)
                        msgUsers.Add(dRow["user_from"].ToString());
                }

            }
            return msgUsers.ToArray();
        }

        [AjaxPro.AjaxMethod]
        public string[] getOnlineUsers(bool chatIsOnline,string currentRoomID)
        {
            List<string> onlineUsers = new List<string>();
            if (ValidateRoomUserStatus())
            {
                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + currentRoomID + "'");
                foreach (DataRow dRow in userRows)
                {
                    onlineUsers.Add ( dRow["UserID"].ToString() );
                }
            }
            return onlineUsers.ToArray();
        }

        /// <summary>
        /// 获取所有好友的状态
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string getAllUserStatus(string currentRoomID)
        {
            string result = string.Empty;
            if (ValidateRoomUserStatus())
            {
                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + currentRoomID + "'");
                foreach (DataRow dRow in userRows)
                {
                    result += dRow["UserID"].ToString() + "=1;";
                }
            }
            return result;
        }

        [AjaxPro.AjaxMethod]
        public void LoginOut(string currentRoomID)
        {
            if (AliApi.appUserId != null && AliApi.appUserId != string.Empty )
            {
                DataRow[] userRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + currentRoomID + "' and UserID='" + currentUserID + "'");
                if (userRows.Length > 0)
                {
                    //移除用户 
                    string newUserNick = userRows[0]["NickName"].ToString();
                    string newUserID = userRows[0]["UserID"].ToString();
                    InsertNewMessage(((newUserNick != "" && newUserNick != null) ? newUserNick : newUserID) + " 已退出聊天室！", true, currentRoomID);                          
                    CommonChatRoomCache.ChatUserTable.Rows.Remove(userRows[0]);                   
                    DataRow[] otherUserRows = CommonChatRoomCache.ChatUserTable.Select("RoomID='" + currentRoomID + "'");
                    if (otherUserRows.Length <= 0)
                    {
                        //移除聊天室
                        DataRow[] roomRows = CommonChatRoomCache.ChatRoomTable.Select("RoomID='" + currentRoomID + "'");
                        if(roomRows .Length >0)
                            CommonChatRoomCache.ChatRoomTable.Rows.Remove(roomRows[0] );
                        //移除聊天室对应的聊天记录
                        DataRow[] chatInfoRows = CommonChatRoomCache.ChatInfoTable.Select("RoomID='" + currentRoomID + "'");
                        if (chatInfoRows.Length > 0)
                        {
                            foreach (DataRow chatInfoRow in chatInfoRows)
                                CommonChatRoomCache.ChatInfoTable.Rows.Remove(chatInfoRow );
                        }
                    }
                }
            }
        }
        #endregion 

        #region 辅助方法
        /// <summary>
        /// 获取当前用户的好友列表
        /// </summary>
        private List<string> GetCurrentUserFriends()
        {
            List<string> friends = new List<string>();
            if (AliApi.appUserId != null && AliApi.appUserId != string.Empty)
            {
                string sqlString = "select * from dbo.cbusergrouplist where cbusergroupid in (select cbusergroupid from dbo.cbusergroup where cbuserid=@myid) ";
                SqlParameter[] sqlparams = new SqlParameter[1];
                sqlparams[0] = new SqlParameter("@myid", AliApi.appUserId);
                DataSet dSet = SqlHelper.Instance.ExecuteQuery(sqlString, sqlparams);
                if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                {                 
                    int totalCount =dSet .Tables [0].Rows.Count ;
                    for (int i = 0; i < totalCount; i++)
                    {
                        friends .Add (dSet .Tables [0].Rows [i]["cbuserid"].ToString ());
                    }
                }
            }
            return friends;
        }
        #endregion

    }                    
}
